package com.example.myapplication444

import android.content.Intent
import android.graphics.Bitmap
import android.os.Bundle
import android.widget.*
import androidx.appcompat.app.AppCompatActivity

class MainActivity : AppCompatActivity() {

    private var name = "阮绿莎"
    private var studentId = "2023110523"
    private var phone = "13800000000"
    private var email = "ruanlvsha@xxx.com"
    private var gender = "女"
    private var hobby = "旅游、阅读"
    private var highScore = 0

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        refreshUI()

        findViewById<Button>(R.id.btnEdit).setOnClickListener {
            val i = Intent(this, EditActivity::class.java)
            i.putExtra("name", name)
            i.putExtra("studentId", studentId)
            i.putExtra("phone", phone)
            i.putExtra("email", email)
            i.putExtra("gender", gender)
            i.putExtra("hobby", hobby)
            startActivityForResult(i, 100)
        }

        findViewById<Button>(R.id.btnGame).setOnClickListener {
            val i = Intent(this, GameActivity::class.java)
            i.putExtra("highScore", highScore)
            startActivityForResult(i, 200)
        }
    }

    private fun refreshUI() {
        findViewById<TextView>(R.id.tvName).text = name
        findViewById<TextView>(R.id.tvStudentId).text = studentId
        findViewById<TextView>(R.id.tvPhone).text = phone
        findViewById<TextView>(R.id.tvEmail).text = email
        findViewById<TextView>(R.id.tvGender).text = gender
        findViewById<TextView>(R.id.tvHobby).text = hobby
        findViewById<TextView>(R.id.tvScore).text = getString(R.string.label_score) + highScore
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (resultCode != RESULT_OK) return
        when (requestCode) {
            100 -> {
                data?.let {
                    name = it.getStringExtra("name") ?: name
                    studentId = it.getStringExtra("studentId") ?: studentId
                    phone = it.getStringExtra("phone") ?: phone
                    email = it.getStringExtra("email") ?: email
                    gender = it.getStringExtra("gender") ?: gender
                    hobby = it.getStringExtra("hobby") ?: hobby

                    // 关键修改：接收并设置头像
                    val avatarBitmap = it.getParcelableExtra<Bitmap>(EditActivity.EXTRA_AVATAR_BITMAP)
                    avatarBitmap?.let { bitmap ->
                        findViewById<ImageView>(R.id.ivAvatar).setImageBitmap(bitmap)
                    }
                }
                refreshUI()
            }
            200 -> {
                highScore = data?.getIntExtra("newHighScore", highScore) ?: highScore
                refreshUI()
            }
        }
    }
}